package jjn.carl.backtrack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;

/**
 * @author Jjn
 * @since 2023/7/24 10:14
 */
public class LeetCode39 {
    
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        Arrays.sort(candidates);
        List<List<Integer>> result = new ArrayList<>();
        if (candidates.length == 0) {
            return result;
        }
        backtrack(target, result, new ArrayList<>(), 0, candidates, 0);
        return result;
    }
    
    private void backtrack(int target, List<List<Integer>> result, List<Integer> path, int sum, int[] candidates, int startIndex) {
        if (sum > target) {
            return;
        }
        if (sum == target) {
            result.add(new ArrayList<>(path));
            return;
        }
        for (int i = startIndex; i < candidates.length; i++) {
            if (sum + candidates[i] > target) {
                break;
            }
            path.add(candidates[i]);
            backtrack(target, result, path, sum + candidates[i], candidates, i);
            path.remove(path.size() - 1);
        }
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int candidateNum = scanner.nextInt();
        int target = scanner.nextInt();
        int[] candidates = new int[candidateNum];
        for (int i = 0; i < candidateNum; i++) {
            candidates[i] = scanner.nextInt();
        }
        List<List<Integer>> lists = new LeetCode39().combinationSum(candidates, target);
        System.out.println(String.join(",", lists.toString()));
    }
}
